import oss2
from django.core.files.storage import Storage
from django.conf import settings
from django.utils.deconstruct import deconstructible


@deconstructible
class CustomOssStorage(Storage):
    def __init__(self):
        try:
            self.auth = oss2.Auth(
                settings.OSS_ACCESS_KEY_ID,
                settings.OSS_ACCESS_KEY_SECRET
            )

            self.bucket = oss2.Bucket(
                self.auth,
                settings.OSS_ENDPOINT,
                settings.OSS_BUCKET_NAME
            )
        except Exception as e:
            raise

    def _save(self, name, content):
        """保存文件到OSS"""
        try:
            # print(f"📤 开始上传文件: {name}")
            # print(f"📝 内容类型: {type(content)}")
            # print(f"📝 内容属性: {dir(content)}")

            # 重置文件指针
            if hasattr(content, 'seek'):
                content.seek(0)
                # print("📝 文件指针重置")

            # 读取内容
            if hasattr(content, 'read'):
                file_content = content.read()
                # print(f"📄 读取文件内容大小: {len(file_content)} bytes")
            else:
                file_content = content
                # print(f"📄 直接使用内容大小: {len(file_content)} bytes")

            # 直接上传到OSS
            # print(f"🔄 正在上传到OSS...")
            result = self.bucket.put_object(name, file_content)

            # print(f"📊 OSS响应状态: {result.status}")
            # print(f"📊 OSS请求ID: {result.request_id}")
            # print(f"📊 OSS响应头: {dict(result.headers)}")

            if result.status == 200:
                # print(f"✅ OSS上传成功: {name}")

                # 立即验证文件是否存在
                exists = self.bucket.object_exists(name)
                # print(f"🔍 立即验证文件存在: {exists}")

                return name
            else:
                # print(f"❌ OSS上传失败: {result.status}")
                raise Exception(f'OSS上传失败: {result.status}')

        except Exception as e:
            # print(f"❌ OSS保存错误: {e}")
            import traceback
            traceback.print_exc()
            raise

    def exists(self, name):
        """检查文件是否存在"""
        try:
            # print(f"🔍 检查文件存在: {name}")
            exists = self.bucket.object_exists(name)
            # print(f"🔍 文件存在结果: {exists}")
            return exists
        except Exception as e:
            # print(f"❌ 检查文件存在错误: {e}")
            return False

    def url(self, name):
        """获取文件URL"""
        if not name:
            return settings.DEFAULT_AVATAR_URL

        url = f'https://{settings.OSS_BUCKET_NAME}.{settings.OSS_ENDPOINT}/{name}'
        # print(f"🌐 生成文件URL: {url}")
        return url

    def delete(self, name):
        """删除文件"""
        try:
            # print(f"🗑️ 删除OSS文件: {name}")
            self.bucket.delete_object(name)
            # print(f"✅ 删除成功")
        except Exception as e:
            print(f"❌ OSS删除错误: {e}")

    def size(self, name):
        """获取文件大小"""
        try:
            info = self.bucket.get_object_meta(name)
            size = info.content_length
            # print(f"📏 文件大小: {name} -> {size} bytes")
            return size
        except Exception as e:
            # print(f"❌ 获取文件大小错误: {e}")
            return 0

    def _open(self, name, mode='rb'):
        """打开文件 - 对于ImageField是必需的"""
        from django.core.files.base import ContentFile
        try:
            # print(f"📖 打开OSS文件: {name}")
            result = self.bucket.get_object(name)
            content = result.read()
            # print(f"📖 读取文件大小: {len(content)} bytes")
            return ContentFile(content, name=name)
        except Exception as e:
            # print(f"❌ 打开OSS文件错误: {e}")
            raise